package cli;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class CommandLineInterface {

    private Map<String, Class<? extends Handler>> map = new HashMap<>();

    public interface Handler {
        void handle(Scanner in, PrintWriter out);
    }

    public static class Exit implements Handler {
        @Override
        public void handle(Scanner in, PrintWriter out) {}
    }

    public static class Help implements Handler {
        @Override
        public void handle(Scanner in, PrintWriter out) {
            out.println("您可以输入以下命令：");
            String[] header = {"命令：", "功能说明："};
            String[][] table = {
                    {"退出", "终止程序"},
                    {"帮助", "显示所有命令"},
                    {"教学班", "显示教学班所有学生的成绩"},
                    {"分数段", "显示成绩的分数段分布"},
                    {"学生", "显示学生的各科成绩和总成绩"},
                    {"排名", "显示学生的排名"},
                    {"课程", "显示课程所有学生的成绩"},
            };
            out.println(new TableLayout(header, table));
        }
    }

    public CommandLineInterface() {
        map.put("退出", Exit.class);
        map.put("帮助", Help.class);
        map.put("教学班", SectionScore.class);
        map.put("分数段", ScoreDistribution.class);
        map.put("学生", StudentScore.class);
        map.put("排名", StudentList.class);
        map.put("课程", CourseScore.class);
    }

    public void run() {
        PrintWriter out = new PrintWriter(System.out, true);
        Scanner in = new Scanner(System.in);
        out.println("欢迎来到学生成绩管理系统。\n如果你对命令不熟悉，可以输入\"帮助\"查看命令手册。");
        while (true) {
            out.printf("-\t-\t-\t-\t-\t-\t-\t-\t-\t-\t\n>>\t");
            String cmd = in.next();
            Class<? extends Handler> handlerClass = map.get(cmd);
            if (handlerClass == null) {
                out.println("命令不存在！");
                continue;
            }
            try {
                Handler handler = handlerClass.newInstance();
                handler.handle(in, out);
                if (handler instanceof Exit)
                    break;
            } catch (InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        out.close();
        in.close();
    }

    public static void main(String[] args) {
        CommandLineInterface cli = new CommandLineInterface();
        cli.run();
    }
}
